get-url.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
  2. import { FileService } from '@/server/modules/files/file.service';
  3. import { MinioService } from '@/server/modules/files/minio.service';
  4. import { ErrorSchema } from '@/server/utils/errorHandler';
  5. import { AppDataSource } from '@/server/data-source';
  6. import { AuthContext } from '@/server/types/context';
  7. import { authMiddleware } from '@/server/middleware/auth.middleware';
  8. // 获取文件URL路由
  9. const getFileUrlRoute = createRoute({
  10. method: 'get',
  11. path: '/url',
  12. middleware: [authMiddleware],
  13. request: {
  14. params: z.object({
  15. id: z.coerce.number().openapi({
  16. param: { name: 'id', in: 'path' },
  17. example: 1,
  18. description: '文件ID'
  19. })
  20. })
  21. },
  22. responses: {
  23. 200: {
  24. description: '获取文件URL成功',
  25. content: {
  26. 'application/json': {
  27. schema: z.object({
  28. url: z.string().url().openapi({
  29. description: '文件访问URL',
  30. example: 'https://minio.example.com/bucket/file-key'
  31. })
  32. })
  33. }
  34. }
  35. },
  36. 404: {
  37. description: '文件不存在',
  38. content: { 'application/json': { schema: ErrorSchema } }
  39. },
  40. 500: {
  41. description: '服务器错误',
  42. content: { 'application/json': { schema: ErrorSchema } }
  43. }
  44. }
  45. });
  46. // 创建文件服务实例
  47. const fileService = new FileService(AppDataSource);
  48. // 创建路由实例
  49. const app = new OpenAPIHono<AuthContext>().openapi(getFileUrlRoute, async (c) => {
  50. try {
  51. const { id } = c.req.valid('param');
  52. const url = await fileService.getFileUrl(id);
  53. return c.json({ url }, 200);
  54. } catch (error) {
  55. const message = error instanceof Error ? error.message : '获取文件URL失败';
  56. const code = (error instanceof Error && error.message === '文件不存在') ? 404 : 500;
  57. return c.json({ code, message }, code);
  58. }
  59. });
  60. export default app;